package utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ThumbNailer {
	public static final String thumbNailSuffix = "_thumbnail.jpg";
	
	public interface ThumbNailable {
		public abstract String getThumbNailPath();
	}
	
	private static String scaleImage(String absoluteFilePath){
    	String filename = absoluteFilePath.substring(absoluteFilePath.lastIndexOf("/") + 1, absoluteFilePath.length() - 4);
    	String absoluteDirectoryPath = absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf("/") + 1);
    	String thumbNailPath = absoluteDirectoryPath + filename + thumbNailSuffix;
    	
    	String retval = "";
    	
	    try {
	        BufferedImage sourceImage = ImageIO.read(new File(absoluteFilePath));
	        int width = sourceImage.getWidth();
	        int height = sourceImage.getHeight();

	        if(width>height){
	            float extraSize = height-100;
	            float percentHight = (extraSize/height)*100;
	            float percentWidth = width - ((width/100)*percentHight);
	            BufferedImage img = new BufferedImage((int)percentWidth, 100, BufferedImage.TYPE_INT_RGB);
	            Image scaledImage = sourceImage.getScaledInstance((int)percentWidth, 100, Image.SCALE_SMOOTH);
	            img.createGraphics().drawImage(scaledImage, 0, 0, null);
	            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
	            img2 = img.getSubimage((int)((percentWidth-100)/2), 0, 100, 100);

	            ImageIO.write(img2, "jpg", new File(thumbNailPath));    
	        } else {
	            float extraSize=    width-100;
	            float percentWidth = (extraSize/width)*100;
	            float  percentHight = height - ((height/100)*percentWidth);
	            BufferedImage img = new BufferedImage(100, (int)percentHight, BufferedImage.TYPE_INT_RGB);
	            Image scaledImage = sourceImage.getScaledInstance(100,(int)percentHight, Image.SCALE_SMOOTH);
	            img.createGraphics().drawImage(scaledImage, 0, 0, null);
	            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
	            img2 = img.getSubimage(0, (int)((percentHight-100)/2), 100, 100);

	            ImageIO.write(img2, "jpg", new File(thumbNailPath));
	        }

	    	//retval is a project relative path
	    	retval = absoluteDirectoryPath.substring(absoluteDirectoryPath.indexOf("CamJam") + 6) + filename + "_thumbnail.jpg";
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return retval;
	}
	
	public static void generateThumbNail(String pathOfImage) {	
		if(pathOfImage != null && pathOfImage != "")
			scaleImage(pathOfImage);
	}
}
